package com.vpen.chat.server;

import com.vpen.chat.server.handler.ChatHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/11/15 15:20
 */
@Slf4j
public class ChatServer {
    /**
     * 端口
     */
    private final int port;

    private final EventLoopGroup bossGroup;
    private final EventLoopGroup workerGroup;

    private final ServerBootstrap serverBootstrap;

    public ChatServer(int port) {
        this.port = port;
        this.bossGroup = new NioEventLoopGroup(1);
        this.workerGroup = new NioEventLoopGroup();
        this.serverBootstrap = new ServerBootstrap();

    }


    public void run() {
        try {
            this.serverBootstrap.group(this.bossGroup, this.workerGroup)
                    .channel(NioServerSocketChannel.class).localAddress(this.port)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 从channel种获取pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加解码处理器
                            pipeline.addLast("stringDecoder", new StringDecoder());
                            // 添加编码处理器
                            pipeline.addLast("stringEncoder", new StringEncoder());
                            // 添加自己的业务处理器
                            pipeline.addLast("chatHandler", new ChatHandler());
                        }
                    });
            log.debug("chat Server 启动......");
            ChannelFuture channelFuture = this.serverBootstrap.bind(this.port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            this.bossGroup.shutdownGracefully();
            this.workerGroup.shutdownGracefully();
        }

    }


}
